import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/ball_appbar.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class MyAvartarsPage extends StatefulWidget {
  const MyAvartarsPage({super.key});

  @override
  State<MyAvartarsPage> createState() => _MyAvartarsPageState();
}

class _MyAvartarsPageState extends State<MyAvartarsPage> {
  List<List<String>> avatars = [];
  String? selected_avatar;

  getAvatars() async {
    final gets = await UserApi.getSystemAvatar() ?? [];
    List<List<String>> n = [];
    for (var i = 0; i < gets.length; i++) {
      final avatar = gets[i];
      if (i % 3 == 0) {
        n.add([]);
      }
      n.last.add(avatar);
    }
    avatars = n;
    update();
  }

  clickUpdate() async {
    if (selected_avatar == null || selected_avatar == User.info?.avatar) {
      Toast.text('头像未更改');
      return;
    }
    int? code = await UserApi.avatarUpdate(selected_avatar!, showLoading: true);
    if (code != null && code == 200) {
      Toast.text('头像替换成功');
      await User.fetchUserInfo(fetchFocus: false);
      Get.back();
      // update();
    }
  }

  @override
  void initState() {
    getAvatars();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar: const BallAppBar(title: "头像替换"),
      body: Stack(
        children: [
          ListView(
            children: [
              header(),
              Container(color: Colours.white, child: defaultAvartars()),
              const SizedBox(
                height: 50,
              )
            ],
          ),
          Positioned(
              bottom: 0, left: 0, right: 0, child: SafeArea(child: submitBtn()))
        ],
      ),
    );
  }

  Widget submitBtn() => Container(
        width: double.infinity,
        margin: const EdgeInsets.all(8),
        height: 44,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colours.main, borderRadius: BorderRadius.circular(8)),
        child: QsText(
          "确认替换",
          color: Colours.white,
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ).tap(clickUpdate);

  Widget avartar(String url) => Container(
        width: 80,
        height: 80,
        clipBehavior: Clip.hardEdge,
        decoration:
            const BoxDecoration(shape: BoxShape.circle, color: Colours.greyEE),
        child: CachedNetworkImage(imageUrl: url),
      );

  Widget header() => Container(
        height: 160,
        width: double.infinity,
        alignment: Alignment.center,
        margin: const EdgeInsets.all(8),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(8)),
        child: avartar(selected_avatar ?? User.info?.avatar ?? ""),
      );

  Widget defaultAvartarCard(String? url) => Expanded(
        child: Container(
          height: 140,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: url != null && selected_avatar == url
                  ? Colours.main.withOpacity(0.1)
                  : Colors.white,
              border: url != null && selected_avatar == url
                  ? Border.all(color: Colours.main, width: 1)
                  : null,
              borderRadius: BorderRadius.circular(8)),
          child: url == null
              ? Container()
              : avartar(url).tap(() {
                  selected_avatar = url;
                  update();
                }),
        ),
      );

  Widget defaultAvartars() => Container(
        margin: const EdgeInsets.symmetric(horizontal: 8),
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
        child: Column(
          children: [
            ...avatars.map((e) => Row(
                  children: [
                    // defaultAvartarCard(),
                    // defaultAvartarCard(),
                    // defaultAvartarCard(),
                    ...e.map((e) => defaultAvartarCard(e)),
                    ...List.generate(
                        3 - e.length, (index) => defaultAvartarCard(null))
                  ],
                )),
          ],
        ),
      );
}
